//
//  ComplaintVC.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 17/3/1.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "ComplaintVC.h"
#import "HeaderMacro.h"
#import "ComplaintListCell.h"
#import "ComplaintResultCell.h"
#import "DLLApiManager.h"
#import <MJRefresh/MJRefresh.h>
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import "ComplaintModel.h"
#import <QXYueYueModels/QXYYUserDriverModel.h>


enum ComplaintShowType {
    
    ComplaintShowNone, // 什么都有
    ComplaintShowListType, // 发起投诉页面
    ComplaintShowResultType // 展示投诉结果页面
};
typedef enum ComplaintShowType ComplaintShowType;


@interface ComplaintVC ()<UITableViewDelegate , UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;


/**
 数据源
 */
@property(nonatomic , strong) NSMutableArray *dataSource;


/**
 投诉页面展示的效果
 */
@property(nonatomic , assign) ComplaintShowType complaintShowType;


/**
 投诉内容
 */
@property(nonatomic , copy) NSString *contents;

@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;

/**
 提交
 */
@property(nonatomic , strong) UIButton *submitBut;

@end

@implementation ComplaintVC
- (NSMutableArray *)dataSource {
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self configureDefaultAttributes];
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        __strong typeof(self) strongSelf = weakSelf;
        // 查询投诉状态
        [strongSelf queryOrderComplaintState];
    }];
    [self.tableView.mj_header beginRefreshing];
}

+ (ComplaintVC *)initComplaintVC {
    
    UIStoryboard *ordersStoryboard = [UIStoryboard storyboardWithName:@"Orders" bundle:[NSBundle mainBundle]];
    
    ComplaintVC *complaintVC = [ordersStoryboard instantiateViewControllerWithIdentifier:@"ComplaintVCID"];
    
    return complaintVC;
}

- (void)configureDefaultAttributes {
    
    // cell 自适应高度
    self.tableView.estimatedRowHeight = 60.0;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.complaintShowType = ComplaintShowNone;
    
    // 设置返回按钮的图片
    [self.backItem setImage:[QXDriverConfiguration imageWithName:@"nav_icon_back_white"]];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (self.complaintShowType == ComplaintShowNone) {
        
        return 0;
    }
    
    return 1;
};

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    NSInteger number = 0;
    switch (self.complaintShowType) {
            
        case ComplaintShowNone: {
            
            number = 0;
            break;
        }
            
        case ComplaintShowListType: {
            
            number = self.dataSource.count;
            break;
        }
        case ComplaintShowResultType: {
            
            return 1;
            break;
        }
        default: {
         
            number = 0;
            break;
        }
    }
    
    return number;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell *cell;
    
    switch (self.complaintShowType) {
        case ComplaintShowNone: {
            
            return [self dealComplaintListCellWithTableView:tableView indexPath:indexPath];
        }
            
        case ComplaintShowListType:
            
            cell = [self dealComplaintListCellWithTableView:tableView indexPath:indexPath];
            break;
        case ComplaintShowResultType:
            
            cell = [self dealComplaintResultCellWithTableView:tableView indexPath:indexPath];
            break;
            
        default:
            break;
    }
    
    return cell;
}

#pragma mark - 投诉列表 Cell UI 处理
- (ComplaintListCell *)dealComplaintListCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    
    ComplaintListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ComplaintListCellID" forIndexPath:indexPath];
    
    ComplaintModel *model = self.dataSource[indexPath.row];
    
    [cell setValueWithComplaintModel:model];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.complaintShowType == ComplaintShowListType) {
        
        return 60;
    }else if (self.complaintShowType == ComplaintShowNone) {
        
        return 0.0;
    }
    else {
        
        return UITableViewAutomaticDimension;
    }
}

#pragma mark - 投诉结果 Cell UI 处理
- (ComplaintResultCell *)dealComplaintResultCellWithTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    
    ComplaintResultCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ComplaintResultCellID" forIndexPath:indexPath];
    
    ComplaintModel *model = self.dataSource[indexPath.row];
    
    [cell setValueWithComplaintModel:model];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.complaintShowType == ComplaintShowListType) {
        
        for (ComplaintModel *model in self.dataSource) {
            
            model.isSelected = NO;
        }
        
        ComplaintModel *model = self.dataSource[indexPath.row];
        model.isSelected = YES;
        if (model.tagName != nil && model.tagName.length > 0) {
            
            self.contents = model.tagName;
        }
        
        [self.tableView reloadData];
    }
}


#pragma mark - UITableViewDelegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 40)];
    headerView.backgroundColor = Color_F3F3F6;
    
    
    UILabel *tilteLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 20, CGRectGetWidth(headerView.frame) - 30, 20)];
    tilteLabel.font = [UIFont systemFontOfSize:16];
    tilteLabel.textColor = Color_6b7886;
    tilteLabel.numberOfLines = 1;
    QXYYUserDriverModel *driverModel = [QXYYUserDriverModel QXYY_unarchiveObject];
    if (driverModel.type == 5 || driverModel.type == 6 || driverModel.type == 7) {
        
        tilteLabel.text = @"请选择投诉该用户的原因";
    }else {
        
        tilteLabel.text = @"请选择投诉该乘客的原因";
    }
    
    tilteLabel.backgroundColor = [UIColor clearColor];
    [headerView addSubview:tilteLabel];
  
    switch (self.complaintShowType) {
        case ComplaintShowNone: {
            
            headerView.hidden = YES;
            break;
        }
        case ComplaintShowListType:
            
            headerView.hidden = NO;
            break;
        case ComplaintShowResultType:
            
            headerView.hidden = YES;
            break;
            
        default:
            break;
    }
    
    return headerView;
};

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    CGFloat height = 0.0;
    
    switch (self.complaintShowType) {
        case ComplaintShowNone: {
            
            height = 0.1;
            break;
        }
        case ComplaintShowListType: {
            height = 40.0;
            break;
        }
        case ComplaintShowResultType: {
            
            height = 0.1;
            break;
        }
        default: {
            height = 0.1;
            break;
        }
    }
    
    return height;;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 105)];
    footerView.backgroundColor = Color_F3F3F6;
    
    UIButton *submitBut = [UIButton buttonWithType:(UIButtonTypeCustom)];
    submitBut.frame = CGRectMake(15, 25, CGRectGetWidth(footerView.frame) - 30, 55);
    submitBut.layer.cornerRadius = 5;
    submitBut.layer.masksToBounds = YES;
    submitBut.backgroundColor = Color_4F5A67;
    submitBut.titleLabel.font = [UIFont systemFontOfSize:17];
    [submitBut setTitle:@"提交" forState:(UIControlStateNormal)];
    [submitBut setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    [submitBut addTarget:self action:@selector(submitButAction:) forControlEvents:(UIControlEventTouchUpInside)];
    [footerView addSubview:submitBut];
    self.submitBut = submitBut;
    
    switch (self.complaintShowType) {
        case ComplaintShowNone: {
            
            footerView.hidden = YES;
            break;
        }
        case ComplaintShowListType: {
            
            footerView.hidden = NO;
            break;
        }
        case ComplaintShowResultType: {
            
            footerView.hidden = YES;
            break;
        }
        default: {
            
            footerView.hidden = YES;
            break;
        }
            
    }
    
    return footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    CGFloat height = 0.0;
    switch (self.complaintShowType) {
        case ComplaintShowNone: {
            
            height = 0.1;
            break;
        }
        case ComplaintShowListType: {
            height = 105.0;
            break;
        }
        case ComplaintShowResultType: {
            
            height = 0.1;
            break;
        }
        default: {
            height = 0.1;
            break;
        }
    }
    
    return height;
}

#pragma mark - action
- (IBAction)backAction:(UIBarButtonItem *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)submitButAction:(UIButton *)sender {
    
    sender.userInteractionEnabled = NO;
    [sender setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    [self submitComplaintRequest];
    
}

#pragma mark - 查询订单投诉状态
/**
 查询订单状态
 */
- (void)queryOrderComplaintState {
    
    NSMutableDictionary *pramaters = [NSMutableDictionary dictionary];
    [pramaters setValue:self.orderUuid forKey:@"orderUuid"]; // 订单id
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverComplaintStateWithParameters:pramaters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.dataSource removeAllObjects];
            [strongSelf.tableView.mj_header endRefreshing];
        });
        
        if (NetWork_Success) {
            
            switch ([data[@"data"][@"status"] integerValue]) { // status：1：待处理，2：正在处理，3：已处理, 其他没有投诉
                case 1:
                case 2:
                case 3: {
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        ComplaintModel *model = [ComplaintModel new];
                        [model setValuesForKeysWithDictionary:data[@"data"]];
                        [strongSelf.dataSource addObject:model];
                        strongSelf.complaintShowType = ComplaintShowResultType; // 展示投诉结果
                        [strongSelf.tableView reloadData];
                    });

                    break;
                }
                default: {
                    dispatch_async(dispatch_get_main_queue(), ^{
                    // 获取投诉标签
                        [strongSelf getComplainMark];
                    });
                    break;
                }
            }
            
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [strongSelf.tableView.mj_header endRefreshing];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
    }];
}


#pragma mark - 获取投诉标签
/**
 获取投诉标签
 */
- (void)getComplainMark {
    
    dispatch_async(dispatch_get_main_queue(), ^{

        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = NO;
    });
    
    [DLLApiManager driverComplaintListWithParameters:nil success:^(id data) {
        
        [self.dataSource removeAllObjects];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:NO];
        });
        
        if (NetWork_Success) {
            
            NSArray *dataArr = data[@"data"];
            if ([dataArr isKindOfClass:[NSArray class]]) {
                
                if (dataArr.count > 0) {
                    
                    for (NSInteger i = 0; i < dataArr.count; i ++) {
                        
                        NSDictionary *dataDic = dataArr[i];
                        ComplaintModel *model = [[ComplaintModel alloc] init];
                        [model setValuesForKeysWithDictionary:dataDic];
                        model.isSelected = NO; // 默认都没有选中
                        [self.dataSource addObject:model];
                    }
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.complaintShowType = ComplaintShowListType; // 展示投诉结果
                        [self.tableView reloadData];
                    });
                }else {
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        self.complaintShowType = ComplaintShowNone; // 展示投诉结果
                        [self.tableView reloadData];
                    });
                }
            }else {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.complaintShowType = ComplaintShowListType; // 展示投诉结果
                    [self.tableView reloadData];
                });
            }
            
        }else {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:self.view hiddenDuration:2.0];
                mb.userInteractionEnabled = NO;
            });
        }
        
    } failure:^(NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //            [MBProgressHUD hideHUDForView:self.view animated:NO];
            [self.tableView.mj_header endRefreshing];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:self.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
    }];
}


#pragma mark - 投诉请求
/**
 发去投诉请求
 */
- (void)submitComplaintRequest {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        MBProgressHUD *mb = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        mb.userInteractionEnabled = NO;
    });
    
    NSMutableDictionary *pramaters = [NSMutableDictionary dictionary];
    [pramaters setValue:self.orderUuid forKey:@"orderUuid"]; // 订单id
    [pramaters setValue:self.contents forKey:@"contents"]; // 投诉内容
    [pramaters setValue:@"" forKey:@"remark"]; // 备注
    
    __weak typeof(self) weakSelf = self;
    [DLLApiManager driverComplaintWithParameters:pramaters success:^(id data) {
        
        __strong typeof(self) strongSelf = weakSelf;
        
        if (NetWork_Success) {
            
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [strongSelf.tableView.mj_header beginRefreshing];
            });
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
            strongSelf.submitBut.userInteractionEnabled = YES;
            [strongSelf.submitBut setTitleColor:Color_4F5A67 forState:(UIControlStateNormal)];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWork_Message onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        
    } failure:^(NSError *error) {
        __strong typeof(self) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:strongSelf.view animated:NO];
            MBProgressHUD *mb = [MBProgressHUD showWithText:NetWorkNotToForce onView:strongSelf.view hiddenDuration:2.0];
            mb.userInteractionEnabled = NO;
        });
        
    }];
}

- (void)dealloc {
 
    NSLog(@"投诉页面销毁了");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
